
<?php
function NewsSort($array,$metodo){
	
	switch ($metodo) {
		case "diario":
				$array_ordenado = sortBySourceName($array);
				break;
		case "peso":
				$array_ordenado = sortByWeight($array);
				break;
	}

	return ($array_ordenado);
}



function sortByWeight($array){
	if (count($array)< 2) {
            return $array;
	}
 
	$pivot = $array[0];
	$left = $right = array();
 
	for ($i = 1; $i < count($array); $i++) {
		if ($array[$i]->getWeight() > $pivot->getWeight()){
			$left[] = $array[$i];
		}
		else{
			$right[] = $array[$i];
		}
	}
 
	return array_merge(sortByWeight($left), array($pivot), sortByWeight($right));
}

function sortBySourceName($array){
	if (count($array)< 2) {
		return $array;
	}
	
	usort($array, "cmp");
	return $array;

}

//The comparison function must return an integer less than, equal to, or greater than zero if the first argument is 
//considered to be respectively less than, equal to, or greater than the second. 
function cmp($a, $b){
	$ret_value;
	//Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.
	$string_ret_val = strcmp($a->getSource(), $b->getSource());
	
	//si son iguales, pregunto por el peso
	if ($string_ret_val == 0){
		if ($a->getWeight() == $b->getWeight()){
			$ret_value = 0;
		}
		else{
			$ret_value = ($a->getWeight() < $b->getWeight()) ? -1 : 1;
		}
	}
	//sino utilizo el valor devuelto por strcmp
	else{
		$ret_value = $string_ret_val;
	}
	return $ret_value;
}

?>